﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Security.AccessControl;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraWizard;
using DevExpress.XtraWizard.Demos.Properties;
using FileManagerGlobal_Library;
using IWshRuntimeLibrary;
using Microsoft.Win32;
using File = System.IO.File;

namespace DevExpress.XtraWizard.Demos {
    public partial class frmMain : XtraForm {
        //Timer progressTimer = null;
        Int32 ltTimer = 0;
        bool finish = false;

        public frmMain() : this(true, WizardStyle.Wizard97) { 
        }

        public frmMain(bool allowAnimation, WizardStyle style) {
            InitializeComponent();
            wizardControl1.AllowTransitionAnimation = allowAnimation;
            wizardControl1.WizardStyle = style;
            memoEdit1.Text = Info.LongText;
            Text += string.Format("      Version: {0}", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
        }

        private void wizardControl1_SelectedPageChanging(object sender, WizardPageChangingEventArgs e) {
            if(e.Page == wpLongText) {
                e.Page.AllowNext = ceLongText.Checked;
                CreateLongTextTimer();
            }
            if(e.PrevPage == wpQuestion && e.Direction == Direction.Forward) 
            if(e.PrevPage == wpProgress && e.Direction == Direction.Backward)
                e.Page = wpQuestion;
            if(e.Page == wpProgress)
                CreateProgressTimer();
            if(e.PrevPage == wpProgress) {
                progressBarControl1.Position = 0;
                lbProgress.Visible = false;
            }
         //   if(e.Page == completionWizardPage1) {
                //if(teRobotTest.Text.ToLower() == "devexpress123") {
                //    completionWizardPage1.Text = "Congratulations – You've Passed All the Way Through!";
                //    completionWizardPage1.FinishText = lbcPlay.SelectedIndex > -1 ?
                //        string.Format("Thank you for completing this XtraWizard feature tour! We can now conclusively state that you are very patient, definitely not a robot, a quick reader, and a fan of {0} just like we are.", GetArtistName(lbcPlay.SelectedValue)) : 
                //        "Thank you for completing this XtraWizard feature tour! We can now conclusively state that you are very patient, a quick reader and definitely not a robot.";
                //}
                //else {
                //    completionWizardPage1.Text = "Sorry, No Robots Allowed";
                //    completionWizardPage1.FinishText = "We are very sorry, but no robots are allowed to continue this wizard. Please click Finish to exit.";
                //}
          //  }
        }

        string GetArtistName(object value) {
            if(value == null) return string.Empty;
            return value.ToString().Substring(0, value.ToString().IndexOf("-") - 1);
        }

        private void wizardControl1_SelectedPageChanged(object sender, WizardPageChangedEventArgs e) {
         // if(e.Page == wpRobotTest)
             //   teRobotTest.Focus();
          //  if(e.Page == wpNoAnswer)
          //      lbcCancel.Top = e.Page.Height - 29;

            if(e.Page == wpProgress)
            {
                e.Page.AllowBack = false;
                e.Page.AllowCancel = false;
                e.Page.AllowNext = false;
                var threadBackgrounWorkher = new BackgroundWorker();
                threadBackgrounWorkher.DoWork += threadBackgrounWorkher_DoWork;
                threadBackgrounWorkher.RunWorkerAsync();
            }
            if(e.Page == completionWizardPage1)
            {
                e.Page.AllowBack = false;
                e.Page.AllowCancel = false;
            }
        }

        private static string InstallFullName = string.Empty;
        private static string AppFolder = string.Empty;
        void threadBackgrounWorkher_DoWork(object sender, DoWorkEventArgs e)
        {
            if(!IsHandleCreated)
                CreateHandle();
              var installPath = Tb_InstallDir.Text;
            if (!Directory.Exists(installPath))
            {
                Invoke((EventHandler) delegate
                                          {
                                              XtraMessageBox.Show("未找到安装目录，请返回重新选择！", "安装提示", MessageBoxButtons.OK,
                                                                  MessageBoxIcon.Information);
                                              wizardControl1.SelectedPage.AllowBack = true;
                                          });
            }
            else
            {
                //MessageBox.Show("Test1");
                Invoke((EventHandler)
                    delegate
                       {
                            try
                            {
                                Lb_InstallInfo.Text = "正在释放安装文件....";
                                Lb_InstallInfo.Update();
                                Lb_InstallInfo.Invalidate();
                                installPath = Path.Combine(installPath, "FilemanagerClient");
                                if (!Directory.Exists(installPath))
                                    Directory.CreateDirectory(installPath);
                                //FilemanagerClient  GlobalVariable.ClientInstallZipName
                                progressBarControl1.Position = 10;
                                progressBarControl1.Update();
                                progressBarControl1.Invalidate();
                                //release zip file
                                var zipFilePath = Path.Combine(Application.StartupPath,
                                                               GlobalVariable.
                                                                   ClientInstallZipName);
                                File.WriteAllBytes(zipFilePath, Resources.FilemanagerClient);

                                progressBarControl1.Position = 40;
                                progressBarControl1.Update();
                                progressBarControl1.Invalidate();
                                Lb_InstallInfo.Text = "正在安装客户端程序....";
                                Lb_InstallInfo.Update();
                                Lb_InstallInfo.Invalidate();
                                ZipHelper.UnZip(zipFilePath, installPath, "", true);

                                var clientAppName = Path.Combine(installPath,
                                                                 GlobalVariable.ClientAppVariable.
                                                                     ClientApplicationName);
                                AppFolder = installPath;
                                InstallFullName = clientAppName;
                                progressBarControl1.Position = 60;
                                progressBarControl1.Update();
                                progressBarControl1.Invalidate();
                                Lb_InstallInfo.Text = "正在注册客户端信息....";
                                Lb_InstallInfo.Update();
                                Lb_InstallInfo.Invalidate();
                                try
                                {
                                    var hkml = Registry.LocalMachine;
                                    var software = hkml.OpenSubKey(GlobalVariable.ClientAppRegistryInfo.RegistryInstallKey,
                                                                   true);
                                    if (null != software)
                                    {
                                        var hasKey =
                                            software.OpenSubKey(
                                                GlobalVariable.ClientAppRegistryInfo.RegistryInstallKey);
                                        if (null != hasKey)
                                            software.DeleteSubKey(GlobalVariable.ClientAppRegistryInfo.RegistryInstallKey);
                                        var installKey =
                                            software.CreateSubKey(
                                                GlobalVariable.ClientAppRegistryInfo.RegistryInstallName);
                                        if (installKey != null)
                                        {
                                            installKey.SetValue(
                                                GlobalVariable.ClientAppRegistryInfo.InstallNameCollection.Default,
                                                clientAppName);
                                            installKey.SetValue(
                                                GlobalVariable.ClientAppRegistryInfo.InstallNameCollection.Path, installPath);
                                        }

                                    }
                                    hkml.Close();
                                }
                                catch (Exception ex)
                                {
                                    XtraMessageBox.Show(ex.Message);
                                }
                                try
                                {
                                    var hkml = Registry.LocalMachine;
                                    var software = hkml.OpenSubKey(
                                        GlobalVariable.ClientAppRegistryInfo.RegistryUnInstallKey, true);
                                    if (null != software)
                                    {
                                        var hasKey =
                                            software.OpenSubKey(
                                                GlobalVariable.ClientAppRegistryInfo.RegistryUnInstallName);
                                        if (null != hasKey)
                                            software.DeleteSubKey(GlobalVariable.ClientAppRegistryInfo.RegistryUnInstallName);
                                        var unInstallKey =
                                            software.CreateSubKey(
                                                GlobalVariable.ClientAppRegistryInfo.RegistryUnInstallName);
                                        var security = new RegistrySecurity();
                                        security.AddAccessRule(new RegistryAccessRule(Environment.UserName,RegistryRights.FullControl, AccessControlType.Allow));
                                        if (null != unInstallKey)
                                        {
                                            try
                                            {
                                                unInstallKey.SetAccessControl(security);
                                            }
                                            catch
                                            {
                                            }
                                            var iconPath = Path.Combine(installPath, "FilemanagerSafe.ico");
                                            var unInstallPath = Path.Combine(installPath, "FileManager_UnInstall.exe");
                                            //FilemanagerSafe.ico
                                            unInstallKey.SetValue(
                                                GlobalVariable.ClientAppRegistryInfo.UninstallNameCollection.Ctext,
                                                "部门文件柜客户端程序会帮助很好的管理部门文件");
                                            unInstallKey.SetValue(
                                                GlobalVariable.ClientAppRegistryInfo.UninstallNameCollection.Curl,
                                                "http://www.grsofter.com/");
                                            unInstallKey.SetValue(
                                                GlobalVariable.ClientAppRegistryInfo.UninstallNameCollection.DisplayIcon,
                                                iconPath);
                                            unInstallKey.SetValue(
                                                GlobalVariable.ClientAppRegistryInfo.UninstallNameCollection.DisplayName,
                                                "文件柜客户端");
                                            unInstallKey.SetValue(
                                                GlobalVariable.ClientAppRegistryInfo.UninstallNameCollection.DisplayVersion,
                                                System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
                                            unInstallKey.SetValue(
                                                GlobalVariable.ClientAppRegistryInfo.UninstallNameCollection.InstallLocation,
                                                installPath);
                                            unInstallKey.SetValue(
                                                GlobalVariable.ClientAppRegistryInfo.UninstallNameCollection.Publisher,
                                                "四川国软科技有限公司");
                                            unInstallKey.SetValue(
                                                GlobalVariable.ClientAppRegistryInfo.UninstallNameCollection.UninstallString,
                                                unInstallPath);
                                        }
                                    }
                                    hkml.Close();
                                }
                                catch (Exception ex)
                                {
                                    XtraMessageBox.Show(ex.Message);
                                }
                                progressBarControl1.Position = 100;
                                progressBarControl1.Update();
                                Lb_InstallInfo.Text = "安装已完成";
                                Lb_InstallInfo.Update();
                                Lb_InstallInfo.Invalidate();
                                wizardControl1.SelectedPage.AllowNext = true;
                                lbProgress.Visible = true;
                            }
                            catch (Exception ex)
                            {
                                XtraMessageBox.Show(ex.Message);
                            }
                        });
            }
        }

        Int32 GetLongTextTime() {
            return (System.Environment.TickCount - ltTimer) / 1000;
        }

        void CreateLongTextTimer() {
            //if(ltTimer == 0)
            //    ltTimer = System.Environment.TickCount;
        }

        void CreateProgressTimer() {
            //if(progressTimer != null) return;
            //wpProgress.AllowNext = false;
            //progressTimer = new Timer();
            //progressTimer.Interval = 40;
            //progressTimer.Tick += new EventHandler(progressTimer_Tick);
            //progressTimer.Start();
        }

        void progressTimer_Tick(object sender, EventArgs e) {
            progressBarControl1.Position++;
            if(progressBarControl1.Position >= 100) {
              //  progressTimer.Stop();
                lbProgress.Visible = true;
                wpProgress.AllowNext = true;
            }
        }

        private void ceLongText_CheckedChanged(object sender, EventArgs e) {
            CheckEdit ce = sender as CheckEdit;
            wpLongText.AllowNext = ce.Checked;
        }

        private void wizardControl1_NextClick(object sender, WizardCommandButtonClickEventArgs e) {
            //if(e.Page == wpLongText && GetLongTextTime() < 60) {
            //    if(XtraMessageBox.Show(this, string.Format("Are you sure that {0} seconds was enough time for you to read all that text?", GetLongTextTime()),
            //        "Long Text Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes) 
            //        ltTimer = -1;
            //    else 
            //        e.Handled = true;
            //}
            if(e.Page == wpQuestion)
            {
                if(string.IsNullOrEmpty(Tb_InstallDir.Text.Trim()))
                {
                    XtraMessageBox.Show("请选择程序安装目录!", "安装提示", MessageBoxButtons.OK, MessageBoxIcon.Information,
                                        MessageBoxDefaultButton.Button2);
                    e.Handled = true;
                    return;
                }
                if(!Directory.Exists(Tb_InstallDir.Text.Trim()))
                {
                    XtraMessageBox.Show("该安装目录不存在，请重新选择!", "安装提示", MessageBoxButtons.OK, MessageBoxIcon.Information,
                    MessageBoxDefaultButton.Button2);
                    e.Handled = true;
                    return;
                }
            }
        }

        private void sbPlay_Click(object sender, EventArgs e) {
            //XtraMessageBox.Show(this, string.Format("Sorry, but we don’t have that song in our library...\r\nBut we agree with you that \"{0}\" is an excellent choice.", lbcPlay.SelectedValue), 
            //    "XtraWizard", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //wizardControl1.SelectedPage = wpLongText;
        }

        private void lbcPlay_SelectedIndexChanged(object sender, EventArgs e) {
           // sbPlay.Enabled = lbcPlay.SelectedIndex > -1; 
        }

        private void wizardControl1_FinishClick(object sender, CancelEventArgs e) {
            finish = true;
            if(Cb_AutoStart.Checked)
            {
                try
                {
                    var runKey = Registry.LocalMachine.OpenSubKey(GlobalVariable.ClientAppRegistryInfo.RegistryAutoStartKey, true);
                    if (null != runKey)
                    {
                        runKey.SetValue(GlobalVariable.ClientAppRegistryInfo.AutoStartNameCollection.RegistryAutoStartName, InstallFullName);
                        runKey.Close();
                    }
                }
                catch (Exception)
                {
                }
            }
            //实例化WshShell对象 
            var shell = new WshShell();
            //通过该对象的 CreateShortcut 方法来创建 IWshShortcut 接口的实例对象 
            var shortcut = (IWshShortcut)shell.CreateShortcut(
                Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "//部门文件柜客户端.lnk");
            //设置快捷方式的目标所在的位置(源程序完整路径) 
            shortcut.TargetPath = InstallFullName;
            //应用程序的工作目录 
            //当用户没有指定一个具体的目录时，快捷方式的目标应用程序将使用该属性所指定的目录来装载或保存文件。 
            shortcut.WorkingDirectory = AppFolder;
            //目标应用程序窗口类型(1.Normal window普通窗口,3.Maximized最大化窗口,7.Minimized最小化) 
            shortcut.WindowStyle = 1;
            //快捷方式的描述 
            shortcut.Description = "部门文件柜客户端";
            //可以自定义快捷方式图标.(如果不设置,则将默认源文件图标.) 
            //shortcut.IconLocation = System.Environment.SystemDirectory + "\\" + "shell32.dll, 165"; 
            //设置应用程序的启动参数(如果应用程序支持的话) 
            //shortcut.Arguments = "/myword /d4s"; 
            //设置快捷键(如果有必要的话.) 
            //shortcut.Hotkey = "CTRL+ALT+D"; 
            //保存快捷方式 
            shortcut.Save();
 
            if (!string.IsNullOrEmpty(InstallFullName))
            {
                var processStartInfo = new ProcessStartInfo { FileName = InstallFullName, WorkingDirectory = AppFolder };
                Process.Start(processStartInfo);
            }
            this.Close();
        }

        private void wizardControl1_CancelClick(object sender, CancelEventArgs e) {
            this.Close();
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e) {
            if(finish)
            {
                DeleteSelf.BeginKillSelf();
                return;
            }
            if(XtraMessageBox.Show(this, "安装尚未完成，您确定要退出安装程序吗?", "安装提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                e.Cancel = true;
            else
            {
                DeleteSelf.BeginKillSelf();
               // Environment.Exit(Environment.ExitCode);
            }
        }

        private void Btn_SelectInstallDir_Click(object sender, EventArgs e)
        {
            var dialog = new FolderBrowserDialog { Description = "请选择程序安装目录" };
            if (dialog.ShowDialog() != DialogResult.OK) return;
            Tb_InstallDir.Text = dialog.SelectedPath;
        }
    }
}
